package bank.driver.local;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import bank.Account;
import bank.Bank;
import bank.InactiveException;
import bank.OverdrawException;

public class LocalBank implements Bank {
	
	private Map<String, LocalAccount> accounts;

	public LocalBank(){
		this.accounts = new HashMap<String, LocalAccount>();
	}
	
	@Override
	public String createAccount(String owner) throws IOException {
		int nr = this.accounts.size();
		LocalAccount a = new LocalAccount(owner,nr);
		this.accounts.put(a.getNumber(), a);
		return a.getNumber();
	}

	@Override
	public LocalAccount getAccount(String number) throws IOException {
		return this.accounts.get(number);
	}

	@Override
	public Set<String> getAccountNumbers() throws IOException {
		Set<String> activeNumbers = new HashSet<String>();
		Set<String> numbers = this.accounts.keySet();
		for (String nr : numbers) {
			if (this.accounts.get(nr).isActive()) {
				activeNumbers.add(nr);
			}
		}
		return activeNumbers;
	}

	@Override
	public boolean removeAccount(String number) throws IOException {
		if (!this.accounts.containsKey(number)){
			return true;
		}
		LocalAccount a = this.accounts.get(number);
		if (a.getBalance() == 0) {
			a.deactivate();
			return true;
		}
		return false;
	}

	@Override
	public void transfer(Account a, Account b, double amount)
			throws IOException, IllegalArgumentException, OverdrawException,
			InactiveException {
		//Exception kommen "von unten"
		a.withdraw(amount);
		b.deposit(amount);
	}
}